/**
 * 配置浏览器本地存储的方式，可直接存储对象数组。
 */

import WebStorageCache from 'web-storage-cache'
import localforage from 'localforage'
import { CACHE_KEY } from '@/enums/CACHE_KEY'

export * from '@/enums/CACHE_KEY'

type CacheType = 'localStorage' | 'sessionStorage'

class Localforage {
  version: string // 系统 indexDB 使用字段最新版本

  constructor() {
    this.version = '1.0.0'
  }

  async get(name: any): Promise<any> {
    try {
      let result = null
      if (name && typeof name === 'string') {
        result = await localforage.getItem(name)
      }
  
      return result
    } catch (err) {
      return null
    }
  }

  async set(name: any, value: any): Promise<boolean> {
    try {
      if (name && typeof name === 'string') {
        await localforage.setItem(name, value)
      }
  
      return true
    } catch (err) {
      return false
    }
  }

  async delete(name: string): Promise<boolean> {
    try {
      if (name && typeof name === 'string') {
        await localforage.removeItem(name)
      }

      return true
    } catch (err) {
      return false
    }
  }

  async updateIndexDBKey() {
    const localVersion = await this.get(CACHE_KEY.OSLOCALFORAGE_VESION)
    if (!localVersion || localVersion !== this.version) {
      this.set(CACHE_KEY.OSLOCALFORAGE_VESION, this.version)
  
      // 逐条清除历史记录
      // this.delete(CACHE_KEY.OSADMIN_ARTICLE_GROUP)
      // ...
    }
  }
}

export const useCache = (type: CacheType = 'localStorage') => {
  const wsCache: WebStorageCache = new WebStorageCache({
    storage: type
  })

  const dbCache = new Localforage()

  return {
    wsCache,
    dbCache,
  }
}
